include!("../dzk/daemon.rs");

use crate::pack::TM_BIN;
use std::{
    process::{Command, Stdio},
    thread,
};

pub fn dzkd_exec(cfg: DaemonCfg) -> Result<()> {
    start_tendermint(&cfg.tendermint_home_dir)
        .c(d!())
        .and_then(|_| exec(cfg).c(d!()))
}

fn start_tendermint(home: &str) -> Result<()> {
    let cmd = format!("{} node --home {}", TM_BIN.as_str(), home);
    thread::spawn(move || {
        pnk!(exec_spawn(&cmd));
    });
    Ok(())
}

fn exec_spawn(cmd: &str) -> Result<()> {
    Command::new("bash")
        .arg("-c")
        .arg(cmd)
        .stdin(Stdio::null())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .spawn()
        .c(d!())?
        .wait()
        .c(d!())
        .map(|exit_status| println!("{}", exit_status))
}
